package com.hefan.common.sequence.dao;

import com.cat.tiger.util.CollectionUtils;
import com.hefan.common.orm.dao.BaseDaoImpl;
import com.hefan.common.sequence.CodeSequence;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ninglijun
 * @description
 */
@Repository
public class CodeSequenceDao extends BaseDaoImpl<CodeSequence> {

    private CodeSequence getBySeqWithLock(String seq) {
        String sql = "select id, sequence, val from code_sequence where sequence = ? and delete_flag = 0 for update";
        List<CodeSequence> sequences = jdbcTemplate.query(sql, new Object[]{seq}, new BeanPropertyRowMapper<CodeSequence>(CodeSequence
                .class));

        if (CollectionUtils.isNotEmpty(sequences)) {
            return sequences.get(0);
        }
        return null;
    }

    public long nextVal(String seq) {
        CodeSequence codeSequence = getBySeqWithLock(seq);
        if (codeSequence == null) {
            codeSequence = new CodeSequence();
            codeSequence.setSequence(seq);
        }
        long nextValue = codeSequence.getVal() + 1;
        codeSequence.setVal(nextValue);
        save(codeSequence);
        return nextValue;
    }

}
